package com.itheima.controller;

import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String pathname;
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        File dir = new File(pathname);
        if (!dir.exists()){
            dir.mkdirs();//判断路径是否存在就，如果不存在就创建
        }
        log.info("文件上传");
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));//得到文件的类型
        String s = UUID.randomUUID().toString() + suffix;//得到文件的整个名称
        file.transferTo(new File(pathname+s));//将文件存入指定的路径，以指定的文件名和类型
        return R.success(s);
    }
    @GetMapping("download")
    public void download(HttpServletResponse response,String name) throws IOException {
        FileInputStream fis = new FileInputStream(new File(pathname, name));
        ServletOutputStream sos = response.getOutputStream();
        IOUtils.copy(fis,sos);

    }
}
